//
//  HomeChatView.swift
//  imprint
//
//  Created by 小柠檬🍋 on 2025/9/7.
//

import SwiftUI

struct HomeChatView: View {
    @EnvironmentObject var userManager: UserManager
    @StateObject var viewModel = HomeChatViewModel()
    @State var bgUrl = ""
    var body: some View {
        ZStack {
            // 背景层
            BackgroundView(url: bgUrl, isMain: true)
            VStack(spacing:0) {
                HStack(alignment:.top,spacing: 0) {//取消之间的间距
                    classsifyView
                        .frame(maxWidth: .infinity)
                    ZStack {
                        Image(.mainIconChat)
                            .resizable()
                            .renderingMode(.template)
                            .scaledToFit()
                            .foregroundColor(themeManager.themeColor)
                            .frame(width: 23, height: 23)
                        //                Text(AiChatExt.getAiCountStr())
                        Text(userManager.getAiCountStr(isShowCount: false))
                            .font(.system(size: 10))
                            .foregroundStyle(themeManager.themeColor)
                            .padding(.top,35)
                    }.padding(.top, -10)//由于timeView自定义字体顶部间距过大
                        .contentShape(Rectangle())
                        .onTapGesture {
                            pathManager.jump(type: JumpType.BUY_COUNT)
                        }
                }.frame(maxWidth: .infinity)
                    .padding(.leading, 5)
                    .padding(.trailing, 20)
                pageView
            }
        }.onChange(of: userManager.isLoginSuc) { value in
            viewModel.getTab()
        }
        .onChange(of: BackupsManager.shared.backupsType) { value in
            viewModel.getTab()
        }.onAppear{
            if !viewModel.isInit {
                viewModel.getTab()
                viewModel.isInit = true
            }
        }
        .background(.bg)
    }
}

extension HomeChatView {
    //标签分类
    var classsifyView: some View {
        ScrollView(.horizontal,showsIndicators: false) {
            VStack(alignment: .leading, spacing: 0){
                //滚动试图（通过HStack监听selectIndex 变化，实现滚动标签）
                ScrollViewReader { value in
                    //横向布局
                    HStack(spacing:0) {
                        ForEach(viewModel.tableItem, id: \.uuid) { item in
                            HStack(spacing: 0) { //间距为0
                                //文本
                                Text(item.name)
                                    .font(.system(size: item.id == viewModel.selectId ? 20 : 15))
                                    .fontWeight(item.id == viewModel.selectId ? .semibold : .regular)
                                    .foregroundColor(.bgNormalText.opacity(item.id == viewModel.selectId ? 1 : 0.3))
                                    .padding(0)
                            }.padding(.horizontal, 7)
                                .padding(.top, 5)
                                .onTapGesture {
                                    withAnimation{
                                        viewModel.selectId = item.id
                                    }
                                    //                                     withAnimation(Animation.linear(duration: 2)) { //加个动画，标题滚动到中间才不会生硬
                                    //                                         value.scrollTo(selectIndex,anchor: .center)
                                    //                                     }
                                }
                            
                        }
                    }.padding(.leading,10).padding(.trailing,10) //内部滚动间距
                    //监听试图，让他滚动的时候居中，不支持16
                        .onReceive(viewModel.$selectId) { newValue in
                            let selectIndex = viewModel.tableItem.firstIndex(where: { $0.id == newValue })
                            withAnimation(Animation.linear(duration: 2)) { //加个动画，标题滚动到中间才不会生硬
                                value.scrollTo(selectIndex,anchor: .center)
                            }
                            if viewModel.tableItem.count > (selectIndex ?? 0) {
                                viewModel.tableItem[selectIndex ?? 0].red = false //取消红点
                            }
                            //由于ChatView在输入法打开的时候，不会调用onAppear和onDisappear
                            if newValue != "0" {
                                bgUrl = ""
                            } else {
                                //更新背景
                                if let firstItem = viewModel.tableItem.first,
                                   let aiRole = firstItem.aiRole {
                                    bgUrl = aiRole.chatBg ?? ""  // 如果 chatBg 为 nil，使用空字符串
                                } else {
                                    bgUrl = ""
                                }
                            }
                            hideKeyboard()
                        }
                }
                //指示器，目前的指示器只能固定大小，应该是需要跟文本一样的宽度才行
                //                     HStack{
                //                         Capsule().fill(Color.red).frame(width: 20,height: 2)
                //                     }.frame(width: 50)
                //                         .offset(x: CGFloat(selectIndex * 50))
                //                         .animation(Animation.linear(duration: 0.2),value: selectIndex)
            }
        }.padding(.trailing,10)
        
    }
}

extension HomeChatView{
    private var pageView : some View {
        TabView(selection: $viewModel.selectId) { //使用selection 就会跟$selectIndex绑定
            ForEach(viewModel.tableItem, id: \.id){ item in
                if item.id == "0" {
                    // 1. 初始化参数
                    let param = {
                        var p = ChatView.Param()
                        p.bean = item.aiRole
                        p.isMain = true
                        return p
                    }() // 立即执行闭包，创建参数
                    ChatView(param: param).id(item.uuid)
                } else if item.id == "1" {
                    ChatRecordView().id(item.uuid).tag(item.id)
                } else if item.id == "2" {
                    ChatListView().id(item.uuid).tag(item.id)
                } else if item.id == "3" {
                    ChatFunctionView().id(item.uuid).tag(item.id)
                }
            }
            
        }.tabViewStyle(PageTabViewStyle(indexDisplayMode: .never))//使用PageTabViewStyle风格
    }
}

#Preview {
    HomeChatView()
}
